// @Author: Duanxj
// @Description:
// @Version: 1.0.0
// @Date: 2021/4/6
// @Time: 18:09

package controller

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/afocus/captcha"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro"
	"github.com/micro/go-plugins/registry/consul"
	"image/png"
	"log"
	getCapCha "microservice/web/proto/getCapCha"
	getMailCode "microservice/web/proto/getMailCode"
	"microservice/web/untils"
)

type ErrRes struct {
	errno  string
	errmsg string
	data   map[string]interface{}
}

// 获取session方法
func GetSession(ctx *gin.Context) {
	err_res := map[string]string{
		"code": untils.RECODE_SESSIONERR,
		"msg":  untils.RecodeText(untils.RECODE_SESSIONERR),
	}
	ctx.JSON(200, err_res)
}

// 获取图片方法
func GetImageCd(ctx *gin.Context) {
	// 获取uuid
	uuid := ctx.Param("uuid")
	// fmt.Println("uuid:", uuid)
	// 指定服务发现
	consulReg := consul.NewRegistry()
	consulService := micro.NewService(
		micro.Registry(consulReg),
	)
	// 初始化客户端
	microClient := getCapCha.NewGetCapChaService("getCapCha", consulService.Client())

	resp, err := microClient.Call(context.TODO(), &getCapCha.Request{Uuid: uuid})
	if err != nil {
		return
	}

	// 将得到的数据反序列化
	var img captcha.Image
	err = json.Unmarshal(resp.Img, &img)
	if err != nil {
		log.Println("反序列化图片失败。。。")
		return
	}
	err = png.Encode(ctx.Writer, img)
	if err != nil {
		log.Println("返回图片失败。。。")
		return
	}
}

func GetMailcd(ctx *gin.Context) {
	// 获取请求参数
	mail := ctx.Param("mail")
	// 从服务注册中心调用微服务
	consulReg := consul.NewRegistry()
	consulService := micro.NewService(
		micro.Registry(consulReg),
	)
	microClient := getMailCode.NewGetMailCodeService("getMailCode", consulService.Client())

	resp, err := microClient.Call(context.TODO(), &getMailCode.Request{Phone: mail, Len: 6})

	if err != nil {
		log.Println(err)
		return
	}
	fmt.Println(resp.MailCode)
	ctx.JSON(200, gin.H{
		"code":  resp.MailCode,
		"errno": untils.RECODE_OK,
	})
}
